package com.thingcom.delinrobot.main.device;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.android.tu.loadingdialog.LoadingDailog;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.thingcom.delinrobot.Common.Constant;
import com.thingcom.delinrobot.Common.Frame.FrameUtils;
import com.thingcom.delinrobot.Common.Frame.GetMainInfo;
import com.thingcom.delinrobot.Common.Frame.SetHomeChange;
import com.thingcom.delinrobot.Common.Frame.SetStartChange;
import com.thingcom.delinrobot.Common.Frame.SetStopChange;
import com.thingcom.delinrobot.Common.Frame.SetTimeToRobot;
import com.thingcom.delinrobot.Common.pjo.FrameType;
import com.thingcom.delinrobot.Data.GizManger;
import com.thingcom.delinrobot.R;
import com.thingcom.delinrobot.base.BaseMainFragment;
import com.thingcom.delinrobot.main.adddevice.DeviceListActivity;
import com.thingcom.delinrobot.utils.CommonDialog;
import com.thingcom.delinrobot.utils.HexStrUtils;
import com.thingcom.delinrobot.utils.MyLog;
import com.thingcom.delinrobot.utils.PreferencesUtil;
import com.thingcom.delinrobot.utils.ToastUtil;
import com.thingcom.delinrobot.view.BGAProgressBar;
import com.thingcom.delinrobot.view.SimpleToolbar;

import java.util.Calendar;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * author : YuFeng
 * e-mail : 923462992@qq.com
 * date   : 2019/11/13
 */
public class DeviceMainFragment extends BaseMainFragment implements GizManger.myGizWifiDeviceListener {

    @BindView(R.id.toolbar_device)
    SimpleToolbar toolbarDevice;
    @BindView(R.id.cl_timer)
    ConstraintLayout clTimer;
    @BindView(R.id.cl_area_set)
    ConstraintLayout clAreaSet;
    @BindView(R.id.tv_warning)
    TextView tvWarning;
    @BindView(R.id.tv_area)
    TextView tvArea;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.main_progressBar)
    BGAProgressBar mainProgressBar;
    @BindView(R.id.tv_robot_status)
    TextView tvRobotStatus;
    @BindView(R.id.cl_device_stop)
    ConstraintLayout clDeviceStop;
    @BindView(R.id.cl_device_home)
    ConstraintLayout clDeviceHome;
    @BindView(R.id.cl_device_start)
    ConstraintLayout clDeviceStart;
    @BindView(R.id.tv_rain)
    ImageView tvRain;
    @BindView(R.id.tv_start_warning)
    TextView tvStartWarning;
    @BindView(R.id.constraintLayout_alert)
    ConstraintLayout constraintLayoutAlert;
    private int robotVersion = 0;
    private Timer timer1;
    private LoadingDailog dialog;
    private static final long WAIT_TIME = 2000L;
    private long TOUCH_TIME = 0;
    private DeviceMainActivity activity;
    public static DeviceMainFragment newInstance() {
        Bundle bundle = new Bundle();
        DeviceMainFragment fragment = new DeviceMainFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @SuppressLint("SetTextI18n")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main_device, container, false);
        unbinder = ButterKnife.bind(this, view);
        initToolbar1(toolbarDevice);
        int electric = PreferencesUtil.getInstance(getContext()).getInt(Constant.ELECTRIC_NUMBER, 100);
        String nextTime = PreferencesUtil.getInstance(getContext()).getString(Constant.MAIN_NEXT_TIME, "09:00");
        int robotStatus = PreferencesUtil.getInstance(getContext()).getInt(Constant.MAIN_ROBOT_STATUS, 2);
        MyLog.i("储存", "onCreateView: "+ robotStatus);
        int robotError = PreferencesUtil.getInstance(getContext()).getInt(Constant.MAIN_ROBOT_ERROR, 0);
        int robotStart = PreferencesUtil.getInstance(getContext()).getInt(Constant.MAIN_ROBOT_START, 1);
        int area = PreferencesUtil.getInstance(getContext()).getInt(Constant.GRASS_AREA, 150);
                switch (robotStatus) {
                    case 0:
                        tvRobotStatus.setText(getString(R.string.robot_status_offline));
                        tvRobotStatus.setTextColor(getResources().getColor(R.color.colorRed));
                        break;
                    case 1:
                        tvRobotStatus.setText(getString(R.string.robot_status_working));
                        tvRobotStatus.setTextColor(getResources().getColor(R.color.white_text));
                        break;
                    case 2:
                        tvRobotStatus.setText(getString(R.string.robot_status_charging));
                        tvRobotStatus.setTextColor(getResources().getColor(R.color.white_text));
                        break;
                    case 3:
                        tvRobotStatus.setText(getString(R.string.robot_status_standby));
                        tvRobotStatus.setTextColor(getResources().getColor(R.color.white_text));
                        break;
                    default:
                        break;
                }


        if(robotError ==0&& robotStart ==1){
            constraintLayoutAlert.setBackgroundColor(getResources().getColor(R.color.edit_normal));
        } else {
            constraintLayoutAlert.setBackgroundColor(getResources().getColor(R.color.colorRed));
        }
        if (robotStart==1){
            tvStartWarning.setText("");
        } else {
            int a = robotStart-1;
            tvStartWarning.setText("F"+a);
        }

        if (robotError ==0){
            switch (robotStatus) {
                case 0:
                    tvWarning.setText(getString(R.string.robot_status_offline));
                    break;
                case 1:
                    tvWarning.setText(getString(R.string.robot_status_working));
                    break;
                case 2:
                    tvWarning.setText(getString(R.string.robot_status_charging));
                    break;
                case 3:
                    tvWarning.setText(getString(R.string.robot_status_standby));
                    break;
                default:
                    break;
            }
        } else {
            tvWarning.setText(getString(R.string.robot_alert) + " E"+ robotError);
        }

        tvArea.setText(area + "m²");
        tvTime.setText(nextTime);
        mainProgressBar.setProgress(electric);

        GizManger.getInstance().setmCallback(this);
        MyLog.i("主页面", "onCreateView: " + "electric" + electric);
        timer1 = new Timer();
        timer1.schedule(new TimerTask() {
            @Override
            public void run() {
                GetMainInfo getMainInfo = new GetMainInfo("00000000");
                GizManger.getInstance().GizWrite(getMainInfo.parse());
            }
        },  300, 5 * 1000);
        Handler handler1 = new Handler();
        handler1.postDelayed(this::sendTime, 4000);
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
         activity = (DeviceMainActivity)context;
    }

    @Override
    public boolean onBackPressedSupport() {
        if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME){
            GizManger.getInstance().unSubcriber();
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            _mActivity.finish();
        }else {
            TOUCH_TIME = System.currentTimeMillis();
            ToastUtil.showToast(_mActivity,getString(R.string.toast_press_again_exit));
        }

        return true;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        GizManger.getInstance().unSubcriber();
//        GizManger.getInstance().removeCallback();
        if (timer1 != null) {
            timer1.cancel();
            timer1 = null;
        }
        if (timer!=null){
            timer.cancel();
        }
    }

    //发送时间
    private void sendTime() {
        Calendar cal = Calendar.getInstance();
        int YY = cal.get(Calendar.YEAR);
        int MM = cal.get(Calendar.MONTH) + 1;
        int DD = cal.get(Calendar.DATE);
        int HH = cal.get(Calendar.HOUR_OF_DAY);
        int NN = cal.get(Calendar.MINUTE);

        byte currentSelectYearHigh = (byte) (YY / 100);
        byte currentSelectYearLow = (byte) (YY % 100);
        byte currentSelectMonth = (byte) MM;
        byte currentSelectDay = (byte) DD;
        byte currentSelectHour = (byte) HH;
        byte currentSelectMinute = (byte) NN;

        //将numpick的数值转换成帧
        byte[] dateByte = new byte[]{currentSelectYearHigh, currentSelectYearLow, currentSelectMonth, currentSelectDay, currentSelectHour
                , currentSelectMinute};
        SetTimeToRobot setTimeToRobot = new SetTimeToRobot("00000000", dateByte);
        GizManger.getInstance().GizWrite(setTimeToRobot.parse());
        //   String dateString = HexUtil.formatHexString(dateByte, true);
    }

    private void initToolbar1(SimpleToolbar toolbar) {
//        if (mOpenDraweListener != null) {
//            mOpenDraweListener.onLockedDrawer();
//        }
        toolbar.setMyLeftIcon(R.drawable.left_arrow_white);
        toolbar.setMinimumHeight(42);
        toolbar.setMyRightIcon1(R.drawable.lock);
        toolbar.setBackgroundColor(getResources().getColor(R.color.black_main));
        toolbar.setTitleStyle(getResources().getColor(R.color.white_main), 13);
        toolbar.setLeftIconClickListener(view -> {
            GizManger.getInstance().unSubcriber();
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            _mActivity.finish();
//                Intent intent = new Intent(getContext(), DeviceListActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
        });
        toolbar.setRightIcon1ClickListener(v -> start(ChangePinBackFragment.newInstance()));
    }

    @OnClick({R.id.cl_device_stop, R.id.cl_device_home, R.id.cl_device_start, R.id.cl_timer, R.id.cl_area_set})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cl_device_stop:
                SetStopChange setStopChange = new SetStopChange("00000000");
                GizManger.getInstance().GizWrite(setStopChange.parse());
                LoadingDailog.Builder loadBuilder=new LoadingDailog.Builder(getContext())
                        .setCancelable(false)
                        .setCancelOutside(false);
                dialog=loadBuilder.create();
                dialog.show();
                timer.start();

                break;
            case R.id.cl_device_home:
                SetHomeChange setHomeChange = new SetHomeChange("00000000");
                GizManger.getInstance().GizWrite(setHomeChange.parse());
                 loadBuilder=new LoadingDailog.Builder(getContext())
                        .setCancelable(false)
                        .setCancelOutside(false);
                dialog=loadBuilder.create();
                dialog.show();
                timer.start();
                break;
            case R.id.cl_device_start:
                CommonDialog fragment = CommonDialog.newInstance(getString(R.string.start_tip), getString(R.string.start_suggestion));
                fragment.setCancelable(false);
                if (getFragmentManager() != null) {
                    fragment.show(getFragmentManager(), "dialog");
                }
                fragment.setOnOkListener(() -> {
                    SetStartChange setStartChange = new SetStartChange("00000000");
                    GizManger.getInstance().GizWrite(setStartChange.parse());
                    LoadingDailog.Builder loadBuilder1 =new LoadingDailog.Builder(getContext())
                            .setCancelable(false)
                            .setCancelOutside(false);
                    dialog= loadBuilder1.create();
                    dialog.show();
                    timer.start();

                });
                break;
            case R.id.cl_timer:
                if (timer1 != null) {
                    timer1.cancel();
                    timer1 = null;
                }
                start(WorkingTimeBackFragment.newInstance());
                break;
            case R.id.cl_area_set:
                if (timer1 != null) {
                    timer1.cancel();
                    timer1 = null;
                }
                start(MowingAreaBackFragment.newInstance(robotVersion));
                break;
        }
    }


    @Override
    public void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice device, boolean isSubscribed) {

    }

    @Override
    public void didReceiveData(GizWifiErrorCode result, GizWifiDevice device, ConcurrentHashMap<String, Object> dataMap, int sn) {
        MyLog.i("收到数据", dataMap.toString());

        if (dataMap.get("binary") != null) {
            // 扩展数据点，key为"kuozhan"
            byte[] bytes = (byte[]) dataMap.get("binary");
            String string = HexStrUtils.bytesToHexString(bytes);
            MyLog.i("收到数据", string);
            byte[] dataArea;
            FrameType identify = FrameUtils.getDataIdentifyEnum(bytes);
            if (identify != null) {
                switch (identify) {
                    case TYPE_FRAME_MAIN_INFO:
                        dataArea = FrameUtils.getDataArea(bytes);
                        String mainInfo = HexStrUtils.bytesToHexString(dataArea);
                        int Power = Integer.valueOf(mainInfo.substring(0, 2), 16);
                        int RobotState = Integer.valueOf(mainInfo.substring(2, 4), 16);
                        int Error = Integer.valueOf(mainInfo.substring(4, 6), 16);
                        int nextHour = Integer.valueOf(mainInfo.substring(6, 8), 16);
                        int nextMinute = Integer.valueOf(mainInfo.substring(8, 10), 16);
                        int area = Integer.valueOf(mainInfo.substring(10, 14), 16);
                        int rain = Integer.valueOf(mainInfo.substring(14, 16), 16);
                        int robot = Integer.valueOf(mainInfo.substring(16, 18), 16);
                        int start = Integer.valueOf(mainInfo.substring(18, 20), 16);
                        Objects.requireNonNull(getActivity()).runOnUiThread(() -> MainInfoUI(Power, RobotState, Error, nextHour, nextMinute, area, rain, robot, start));

                        MyLog.i("mainInfo", "didReceiveData: " + "power:" + Power + "RobotState:"
                                + RobotState + "Error:" + Error + "nextHour:" + nextHour + "nextMinute:" + nextMinute + "area:" + area);
                        break;
                    case TYPE_FRAME_MAIN_HOME:
                    case TYPE_FRAME_MAIN_STOP:
                    case TYPE_FRAME_MAIN_START:
                        dataArea = FrameUtils.getDataArea(bytes);
                        String homeStatus = HexStrUtils.bytesToHexString(dataArea);
                        MyLog.i("start123", "didReceiveData: " + homeStatus);
                        if (timer!=null){
                            timer.cancel();
                        }
                        if (dialog!=null){
                            dialog.dismiss();
                        }
                        if (homeStatus.equals("01")) {
                            Toast.makeText(getContext(), getString(R.string.success_toast), Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getContext(), getString(R.string.fail_toast), Toast.LENGTH_SHORT).show();
                        }
                        break;
                    default:
                        break;
                }
            }


        }
    }

    @Override
    public void didGetHardwareInfo(GizWifiErrorCode result, GizWifiDevice device, ConcurrentHashMap<String, String> hardwareInfo) {

    }

    @Override
    public void didSetCustomInfo(GizWifiErrorCode result, GizWifiDevice device) {

    }

    @Override
    public void didUpdateNetStatus(GizWifiDevice device, GizWifiDeviceNetStatus netStatus) {
        if (this.getContext() != null) {
            if (netStatus != GizWifiDeviceNetStatus.GizDeviceControlled) {

                MyLog.i("网络变化", "didUpdateNetStatus: "+123);
                if (device.isSubscribed()) {
                    GizManger.getInstance().unSubcriber();
                }

                Intent intent = new Intent(getContext(), DeviceListActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        }

    }

    @SuppressLint("SetTextI18n")
    private void MainInfoUI(int power, int RobotState, int Error, int nextHour, int nextMinute, int area, int rain, int robot, int start) {
        //   Toast.makeText(getContext(), "电量" + power, Toast.LENGTH_SHORT).show();
        mainProgressBar.setProgress(power);
        MyLog.i("主页面", "MainInfoUI: " + "electric" + power+"  robot:"+robot);
        PreferencesUtil.getInstance(getContext()).putInt(Constant.ELECTRIC_NUMBER, power);
        PreferencesUtil.getInstance(getContext()).putInt(Constant.MAIN_ROBOT_ERROR, Error);
        PreferencesUtil.getInstance(getContext()).putInt(Constant.MAIN_ROBOT_START, start);
        // Toast.makeText(getContext(), "robot" + robot, Toast.LENGTH_SHORT).show();

        String remark = GizManger.getInstance().getDevice().getRemark();
        if (!remark.equals(String.valueOf(robot-18))){
            GizManger.getInstance().getDevice().setCustomInfo(String.valueOf(robot-18),GizManger.getInstance().getDevice().getAlias());
        }
        robotVersion = robot;
        if(Error==0&&start==1){
            constraintLayoutAlert.setBackgroundColor(getResources().getColor(R.color.edit_normal));
        } else {
            constraintLayoutAlert.setBackgroundColor(getResources().getColor(R.color.colorRed));
        }
        switch (start) {
            case 1:
                tvStartWarning.setText("");
                break;
            case 2:
                tvStartWarning.setText("F1");
                break;
            case 3:
                tvStartWarning.setText("F2");
                break;
            case 4:
                tvStartWarning.setText("F3");
                break;
            case 5:
                tvStartWarning.setText("F4");
                break;
        }
        if (Error==0){
            switch (RobotState) {
                case 0:
                    tvWarning.setText(getString(R.string.robot_status_offline));
                    break;
                case 1:
                    tvWarning.setText(getString(R.string.robot_status_working));
                    break;
                case 2:
                    tvWarning.setText(getString(R.string.robot_status_charging));
                    break;
                case 3:
                    tvWarning.setText(getString(R.string.robot_status_standby));
                    break;
                default:
                    break;
            }
        } else {
            tvWarning.setText(getString(R.string.robot_alert) + " E"+Error);
        }

        switch (RobotState) {
            case 0:
                tvRobotStatus.setText(getString(R.string.robot_status_offline));
                PreferencesUtil.getInstance(getContext()).putInt(Constant.MAIN_ROBOT_STATUS, RobotState);
                tvRobotStatus.setTextColor(getResources().getColor(R.color.colorRed));
                break;
            case 1:
                tvRobotStatus.setText(getString(R.string.robot_status_working));
                PreferencesUtil.getInstance(getContext()).putInt(Constant.MAIN_ROBOT_STATUS, RobotState);
                tvRobotStatus.setTextColor(getResources().getColor(R.color.white_text));
                break;
            case 2:
                tvRobotStatus.setText(getString(R.string.robot_status_charging));
                PreferencesUtil.getInstance(getContext()).putInt(Constant.MAIN_ROBOT_STATUS, RobotState);
                tvRobotStatus.setTextColor(getResources().getColor(R.color.white_text));
                break;
            case 3:
                tvRobotStatus.setText(getString(R.string.robot_status_standby));
                tvRobotStatus.setTextColor(getResources().getColor(R.color.white_text));
                PreferencesUtil.getInstance(getContext()).putInt(Constant.MAIN_ROBOT_STATUS, RobotState);
                break;
            default:
                break;
        }
        switch (rain) {
            case 0:
                activity.runOnUiThread(() -> tvRain.setVisibility(View.GONE));
                break;

            case 85:
                activity.runOnUiThread(() -> tvRain.setVisibility(View.VISIBLE));
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + rain);
        }
        String nextWorking = (nextHour < 10 ? "0" + nextHour : String.valueOf(nextHour)) + ":" + (nextMinute < 10 ? "0" + nextMinute : String.valueOf(nextMinute));
        String mowingArea = area + "m²";
        tvTime.setText(nextWorking);
        PreferencesUtil.getInstance(getContext()).putString(Constant.MAIN_NEXT_TIME, nextWorking);
        tvArea.setText(mowingArea);
        PreferencesUtil.getInstance(getContext()).putInt(Constant.GRASS_AREA, area);
    }


    /**
     * 开始进度
     */

    private CountDownTimer timer = new CountDownTimer(10000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            Toast.makeText(getContext(),"time out ",Toast.LENGTH_SHORT).show();
            if (dialog!=null){
                dialog.dismiss();
            }
        }
    };
}
